package ro.gateway.aida.servlet;

import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ro.gateway.aida.db.DBFilesPersMan;
import ro.gateway.aida.db.DBPersistenceToken;
import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.fnd.FndPersMan;
import ro.gateway.aida.fnd.FundingItem;
import ro.gateway.aida.obj.AIDADocument;
import ro.gateway.aida.obj.AIDALocation;
import ro.gateway.aida.obj.AIDAObjSector;
import ro.gateway.aida.obj.Activity;
import ro.gateway.aida.obj.AidaResource;
import ro.gateway.aida.obj.GenericActivityProperty;
import ro.gateway.aida.obj.OrganizationInv;
import ro.gateway.aida.obj.PersonInv;
import ro.gateway.aida.obj.db.AIDAActivityObjectDB;
import ro.gateway.aida.obj.db.AIDADocumentDB;
import ro.gateway.aida.obj.db.AIDALocationDB;
import ro.gateway.aida.obj.db.AIDAObjSectorDB;
import ro.gateway.aida.obj.db.AIDAResourceDB;
import ro.gateway.aida.obj.db.ActivityDB;
import ro.gateway.aida.obj.db.ActivityRelationDB;
import ro.gateway.aida.obj.db.BookmarkDB;
import ro.gateway.aida.obj.db.ContactInfoPMan;
import ro.gateway.aida.obj.db.DBStuff;
import ro.gateway.aida.obj.db.GenericActivityPropertyDB;
import ro.gateway.aida.obj.db.OrganizationInvDB;
import ro.gateway.aida.obj.db.PersonInvDB;
import ro.gateway.aida.usr.Arbiter;
import ro.gateway.aida.usr.Perms;
import ro.gateway.aida.utils.HttpUtils;


/**
 * Created by IntelliJ IDEA.
 * User: xblue
 * Date: Dec 3, 2003
 * Time: 4:04:11 PM
 * To change this template use Options | File Templates.
 */
public class DeleteProjectAction extends Action {
	public ActionForward execute(ActionMapping mapping,
						    ActionForm form,
						    HttpServletRequest request,
						    HttpServletResponse response)
		 throws Exception {
		ServletContext application = this.getServlet().getServletContext();
		long project_id = HttpUtils.getLong(request, "id", -1);
		PersistenceToken xtoken = PersistenceManager.
			 tokenLookup(application);
		Arbiter ar = Arbiter.getManager(xtoken);
		if (!ar.canDo(request,
			 Perms.EDIT_OBJECT, project_id, Arbiter.PROJECT_TYPE)) {
			return mapping.findForward("norights");
		}

		try {
			DBPersistenceToken token = (DBPersistenceToken) PersistenceManager.
				 tokenLookup(application);
			String application_root = application.getRealPath("/");
			DBFilesPersMan filepman = DBFilesPersMan.getManager(token);

			// get logo and documents
			AIDADocument[] docs = AIDADocumentDB.getManager(token).getForActivity(project_id);
			if (docs != null && docs.length > 0) {
				for (int i = 0; i < docs.length; i++) {
					filepman.deleteFile(docs[i].getRelativeLink());
//                              File tmp_file = new File( application_root + docs[ i ].getRelativeLink() );
//                              if ( tmp_file.exists() )
//                              {
//                                    tmp_file.delete();
//                              }
				}
			}

			Activity project = ActivityDB.
				 getManager(token).getAllDataById(project_id);
			if (project.getLogo_url() != null) {
				filepman.deleteFile(project.getLogo_url());
//                        File tmp_file = new File( application_root + project.getLogo_url() );
//                        if ( tmp_file.exists() )
//                        {
//                              tmp_file.delete();
//                        }
			}

			delete_for_activity(token, project);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		response.sendRedirect(request.getContextPath() + "/desktop.do");
		return null;
//            return mapping.findForward( "homepage" );
	}

	private void delete_for_activity(DBPersistenceToken token,
							   Activity bean)
		 throws SQLException {
		long id = bean.getId();
		DBStuff.getManager(token).deleteDonorIdsForActivity(id);
		BookmarkDB.getManager(token).deleteAllRelated(bean.getId());
		AIDAActivityObjectDB.getManager(token).delete(id);

		//ab.track((int)user_id,(int)act_id,Arbiter.PROJECT_TYPE);
		ActivityRelationDB.getManager(token).delete_for_activity(id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_titles", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_ext_reasons", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_descriptions", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_objectives", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_results", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_status", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_keywords", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_bencomments", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_notefields1", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_notefields2", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_notefields3", id);
		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_notefields4", id);

		GenericActivityProperty[] components = bean.getComponents();

		if (components == null)
			components = new GenericActivityProperty[0];

		GenericActivityPropertyDB.getManager(token).deleteForActivity("gen_components", id);

		OrganizationInv[] organizations = bean.getOrganizations();

		if (organizations == null)
			organizations = new OrganizationInv[0];

		OrganizationInvDB oidb = OrganizationInvDB.getManager(token);
		oidb.deleteForActivity(id);

		PersonInv[] persons = bean.getPersons();

		if (persons == null)
			persons = new PersonInv[0];

		PersonInvDB.getManager(token).deleteForActivity(id);

		AIDADocument[] documents = bean.getDocuments();

		if (documents == null)
			documents = new AIDADocument[0];

		AIDADocumentDB.getManager(token).deleteForActivity(id);

		AidaResource[] resources = bean.getResources();

		if (resources == null)
			resources = new AidaResource[0];

		AIDAResourceDB.getManager(token).delete_for_activity(id);

		AIDALocation[] locations = bean.getLocations();

		if (locations == null)
			locations = new AIDALocation[0];

		AIDALocationDB.getManager(token).delete_for_activity(id);

		AIDAObjSector[] sectors = bean.getSectors();

		if (sectors == null)
			sectors = new AIDAObjSector[0];

		AIDAObjSectorDB.getManager(token).
			 delete_for_activity(id);

		FundingItem[] funding_items = bean.getFunding_itemsArray();

		if (funding_items == null)
			funding_items = new FundingItem[0];

		FndPersMan.getManager(token).deleteForActivity(id);
		ContactInfoPMan.getManager(token).removeForActivity(id);
		ActivityDB.getManager(token).deleteBeneficiaries(bean);

		DBStuff.getManager(token).delete_cats_for_activity(id);
		DBStuff.getManager(token).delete_objects(id);
		ActivityDB.getManager(token).
			 delete(id);


	}
}
